package com.web.gatewayservice.filter;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关统一异常处理
 */
@Order(-1)
@Configuration
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GatewayExceptionHandler.class);

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex){
        ServerHttpResponse response = exchange.getResponse();
        //首先检查响应是否已经提交（即是否已经发送给客户端）。如果已提交，则直接返回包含异常的Mono。
        if (exchange.getResponse().isCommitted()){
            return Mono.error(ex);
        }
        String msg = "";
        if (ex instanceof NotFoundException) {
            msg = "服务器迷路啦，30秒后再重试一下. ";
        }
        else if (ex instanceof ResponseStatusException){
            ResponseStatusException responseStatusException = (ResponseStatusException) ex;
            msg = responseStatusException.getMessage();
        }
        else{
            msg = "内部服务器异常，请联系管理员";
        }

        log.error("[网关异常处理]请求路径:{},异常信息:{}", exchange.getRequest().getPath(), ex.getMessage());

        return write(response, MediaType.APPLICATION_JSON_VALUE, HttpStatus.OK, msg);
    }

    /**
     * 响应
     */
    public static Mono<Void> write(ServerHttpResponse response, String contentType, HttpStatus status, Object value){
        response.setStatusCode(status);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, contentType);
        //通用的响应实体类，使用自己定义的通用返回类就行
        DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONString(value).getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }
}
